﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using Adex;
using MediaMonitor.Common;
using MediaMonitor.Controls;
using Telerik.Web.UI;
using System.Web.Services;
using iTextSharp;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.Collections;


namespace MediaMonitor.Users
{
    public partial class report_news_filter : System.Web.UI.Page
    {

        DateTime sDate = DateTime.MinValue, eDate = DateTime.MinValue;
        private int mediaTypeCode = 0;
        private string mediaCodes = "", categoryCode = "", productCode="";
        private int programCode = 0;
        private int sectorCode = 0, subSectorCode = 0;
        int advertiserCode = 0;
        int sPrice = 0, ePrice = 0;
        private string newsMediaType = "";
        private int newsTypeCode = 0;
        private int sectionCode = 0;

        string days = "";
        bool firstAppearanceOnly = false;
        bool DownloadOnly = false;
        bool DownloadOnlyProduct = false;

        private iTextSharp.text.Font PDF_FONT_DEFAULT;
        private iTextSharp.text.Font PDF_FONT_BOLD;
        private iTextSharp.text.Font PDF_FONT_GRAY;
        private iTextSharp.text.Font PDF_FONT_HEADING;
        private iTextSharp.text.Font PDF_FOONT_SMALL;
        private iTextSharp.text.Font PDF_FONT_SMALL_BOLD;

        protected void Page_Load(object sender, EventArgs e)
        {



            if (!IsPostBack)
            {
                Utility.AddDateControlToPage(this.Page);


                SetCalendarDates();
                //calS.SelectedDate = DateTime.Now.Date;
                //calE.SelectedDate = DateTime.Now.Date;

                FillMediaTypes();
                FillSectors();
                FillSubSectors();
                FillCategories();

                FillSections();
                FillNewsMediaTypes();
                FillNewsTypes();


                FillAdvertisers();

            }
            else
            {
                PDF_FONT_DEFAULT = new Font(Font.FontFamily.HELVETICA, 12, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);

                PDF_FONT_BOLD = new Font(Font.FontFamily.HELVETICA, 12, iTextSharp.text.Font.BOLD, BaseColor.BLACK);

                PDF_FONT_GRAY = new Font(Font.FontFamily.HELVETICA, 12, iTextSharp.text.Font.NORMAL, BaseColor.GRAY);

                PDF_FONT_HEADING = new Font(Font.FontFamily.HELVETICA, 14, iTextSharp.text.Font.NORMAL, BaseColor.LIGHT_GRAY);

                PDF_FOONT_SMALL = new Font(Font.FontFamily.HELVETICA, 10, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
                PDF_FONT_SMALL_BOLD = new Font(Font.FontFamily.HELVETICA, 10, iTextSharp.text.Font.BOLD, BaseColor.BLACK);

            }
        }

        private void FillNewsTypes()
        {
            SqlDataReader rd = (SqlDataReader)NewsLog.Query().DISTINCT().SetSelectList("NewsTypeCode, NewsTypeName").ExecuteReader();
            lstNewsType.DataSource = rd;
            lstNewsType.DataTextField = "NewsTypeName";
            lstNewsType.DataValueField = "NewsTypeCode";
            lstNewsType.DataBind();
            rd.Close();
            lstNewsType.Items.Insert(0, new System.Web.UI.WebControls.ListItem("- SELECT -", "0"));
        }

        private void FillNewsMediaTypes()
        {
            SqlDataReader rd = (SqlDataReader)NewsLog.Query().DISTINCT().SetSelectList("NewsMediaType").ExecuteReader();
            lstNewsMediaType.DataSource = rd;
            lstNewsMediaType.DataTextField = "NewsMediaType";
            lstNewsMediaType.DataValueField = "NewsMediaType";
            lstNewsMediaType.DataBind();
            rd.Close();
            lstNewsMediaType    .Items.Insert(0, new System.Web.UI.WebControls.ListItem("- SELECT -", ""));
        }

        private void FillSections()
        {
            SqlDataReader rd = (SqlDataReader) NewsSection.Query().DISTINCT().ExecuteReader();
            lstSection.DataSource = rd;
            lstSection.DataTextField = "SectionName";
            lstSection.DataValueField = "SectionCode";
            lstSection.DataBind();
            rd.Close();
            lstSection.Items.Insert(0, new System.Web.UI.WebControls.ListItem("- SELECT -", "0"));
        }

        private void SetCalendarDates()
        {


            DataTable dt = NewsLog.Query().DISTINCT().SetSelectList("RFDate").ExecuteDataSet().Tables[0];


            foreach (DataRow dr in dt.Rows)
            {

                RadCalendarDay d1 = new RadCalendarDay(calS);
                d1.Date = Utility.ToDateTime(dr["RFDate"]);
                d1.IsDisabled = false;
                d1.IsSelectable = true;

                d1.ItemStyle.BackColor = System.Drawing.Color.PowderBlue;
                d1.ItemStyle.ForeColor = System.Drawing.Color.White;

                calS.SpecialDays.Add(d1);

                RadCalendarDay d2 = new RadCalendarDay(calE);
                d2.Date = Utility.ToDateTime(dr["RFDate"]);
                d2.IsDisabled = false;
                d2.IsSelectable = true;

                d2.ItemStyle.BackColor = System.Drawing.Color.PowderBlue;
                d2.ItemStyle.ForeColor = System.Drawing.Color.White;


                calE.SpecialDays.Add(d2);
            }



        }


        protected void calS_ViewChanged(object sender, EventArgs e)
        {
            for (DateTime dt = calS.CalendarView.ViewStartDate; dt <= calS.CalendarView.ViewEndDate; dt.AddDays(1))
            {

            }
        }

        private static DataSet GetLookupDataSet()
        {

            if (HttpContext.Current.Cache["dsLookUpByUser_NS_" + AppUser.CurrUserID.ToString()] == null)
            {
                DataSet ds = SPs.GetLookupTables(AppUser.CurrUserID, "NS").GetDataSet();
                ds.Tables[0].TableName = "MediaType";
                ds.Tables[1].TableName = "Media";
                ds.Tables[2].TableName = "Agency";
                ds.Tables[3].TableName = "Advertiser";
                ds.Tables[4].TableName = "Brand";
                ds.Tables[5].TableName = "Sector";
                ds.Tables[6].TableName = "SubSector";
                ds.Tables[7].TableName = "Category";
                ds.Tables[8].TableName = "Product";
                ds.Tables[9].TableName = "ProdVersion";
                // ds.Tables[10].TableName = "Program";

                HttpContext.Current.Cache.Insert("dsLookUpByUser_NS_" + AppUser.CurrUserID.ToString(), ds, null, DateTime.Now.AddMinutes(60), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Normal, null);

                return ds;
            }
            else
            {
                return ((DataSet)(HttpContext.Current.Cache["dsLookUpByUser_NS_" + AppUser.CurrUserID.ToString()]));
            }
        }





        #region FillLists


        private void FillSectors()
        {
            DataTable dt = GetLookupDataSet().Tables[5];

            string filter = "1=1";
            switch (lstMediaType.SelectedValue)
            {
                case "1":
                    {
                        filter += " AND MediaType = 'TVCR' AND  TV = 1";
                        break;
                    }

                case "3":
                    {
                        filter += " AND MediaType = 'TVCR'  AND RD = 1";
                        break;
                    }
                case "5":
                    {
                        filter += " AND MediaType = 'TVCR'  AND CB = 1";
                        break;
                    }
                case "6":
                    {
                        filter += " AND MediaType = 'PR' AND PR = 1";
                        break;
                    }
                case "7":
                    {
                        filter += " AND MediaType = 'OD' AND OD = 1";
                        break;
                    }
                case "8":
                    {
                        filter += " AND MediaType = 'NS' AND NS = 1";
                        break;
                    }
            }

            string sort = "SectorName";

            DataView dv = new DataView(dt, filter, sort, DataViewRowState.OriginalRows);
            DataTable dtcolumns = dv.ToTable(true, "SectorID", "SectorName");

            if (dtcolumns.Rows.Count > 0)
            {
                dtcolumns = RemoveDuplicateRows(dtcolumns, "SectorName");
                lstSector.DataSource = dtcolumns;
                lstSector.DataBind();
            }
            
            lstSector.Items.Insert(0, new System.Web.UI.WebControls.ListItem("- ALL -", "0"));
        }

        public DataTable RemoveDuplicateRows(DataTable dTable, string colName)
        {
            Hashtable hTable = new Hashtable();
            ArrayList duplicateList = new ArrayList();

            //Add list of all the unique item value to hashtable, which stores combination of key, value pair.
            //And add duplicate item value in arraylist.
            foreach (DataRow drow in dTable.Rows)
            {
                if (hTable.Contains(drow[colName]))
                    duplicateList.Add(drow);
                else
                    hTable.Add(drow[colName], string.Empty);
            }

            //Removing a list of duplicate items from datatable.
            foreach (DataRow dRow in duplicateList)
                dTable.Rows.Remove(dRow);

            //Datatable which contains unique records will be return as output.
            return dTable;
        }
        
        private void FillSubSectors()
        {
            DataTable dt = GetLookupDataSet().Tables[6];

            string filter = "1=1";
            switch (lstMediaType.SelectedValue)
            {
                case "1":
                    {
                        filter += " AND MediaType = 'TVCR'  AND TV = 1";
                        break;
                    }

                case "3":
                    {
                        filter += " AND MediaType = 'TVCR'  AND RD = 1";
                        break;
                    }
                case "5":
                    {
                        filter += " AND MediaType = 'TVCR'  AND CB = 1";
                        break;
                    }
                case "6":
                    {
                        filter += " AND MediaType = 'PR' AND PR = 1";
                        break;
                    }
                case "7":
                    {
                        filter += " AND MediaType = 'OD' AND OD = 1";
                        break;
                    }
                case "8":
                    {
                        filter += " AND MediaType = 'NS' AND NS = 1";
                        break;
                    }
            }

            filter += lstSector.SelectedValue != "0" ? " AND SectorID=" + lstSector.SelectedValue : "";

            string sort = "SubSectorName";

            DataView dv = new DataView(dt, filter, sort, DataViewRowState.OriginalRows);

            DataTable dtcolumns = dv.ToTable(true, "SubSectorID", "SubSectorName");

            if (dtcolumns.Rows.Count > 0)
            {
                dtcolumns = RemoveDuplicateRows(dtcolumns, "SubSectorName");

                lstSubSector.DataSource = dtcolumns;
                lstSubSector.DataBind();
            }

            lstSubSector.Items.Insert(0, new System.Web.UI.WebControls.ListItem("- ALL -", "0"));
        }

        private void FillCategories()
        {
            DataTable dt = GetLookupDataSet().Tables[7];

            string filter = "1=1";
            switch (lstMediaType.SelectedValue)
            {
                case "1":
                    {
                        filter += " AND MediaType='TVCR' AND TV = 1";
                        break;
                    }

                case "3":
                    {
                        filter += " AND MediaType='TVCR' AND RD = 1";
                        break;
                    }
                case "5":
                    {
                        filter += " AND MediaType='TVCR' AND CB = 1";
                        break;
                    }
                case "6":
                    {
                        filter += " AND MediaType='PR' AND PR = 1";
                        break;
                    }
                case "7":
                    {
                        filter += " AND MediaType='OD' AND OD = 1";
                        break;
                    }
                case "8":
                    {
                        filter += " AND MediaType='NS' AND NS = 1";
                        break;
                    }
            }

            // filter += lstSector.SelectedValue != "0" ? " AND SectorCode=" + lstSector.SelectedValue : "";
            filter += lstSubSector.SelectedValue != "0" ? " AND SubSectorID=" + lstSubSector.SelectedValue : "";

            string sort = "CategoryName";

            DataView dv = new DataView(dt, filter, sort, DataViewRowState.OriginalRows);
            DataTable dtcolumns = dv.ToTable(true, "CategoryID", "CategoryName");

            if (dtcolumns.Rows.Count > 0)
            {
                dtcolumns = RemoveDuplicateRows(dtcolumns, "CategoryName");
                chkCategory.DataSource = dtcolumns;
                chkCategory.DataBind();
            }

           
        }

        private void FillAdvertisers()
        {
            DataTable dt = GetLookupDataSet().Tables[3];

            string filter = "1=1";
            switch (lstMediaType.SelectedValue)
            {
                case "1":
                    {
                        filter += " AND MediaType='TVCR' AND TV = 1";
                        break;
                    }

                case "3":
                    {
                        filter += " AND MediaType='TVCR' AND RD = 1";
                        break;
                    }
                case "5":
                    {
                        filter += " AND MediaType='TVCR' AND CB = 1";
                        break;
                    }
                case "6":
                    {
                        filter += " AND MediaType='PR' AND PR = 1";
                        break;
                    }
                case "7":
                    {
                        filter += " AND MediaType='OD' AND OD = 1";
                        break;
                    }
                case "8":
                    {
                        filter += " AND MediaType='NS' AND NS = 1";
                        break;
                    }
            }

            string sort = "AdvertiserName";

            DataView dv = new DataView(dt, filter, sort, DataViewRowState.OriginalRows);

            lstAdvertiser.DataSource = dv;
            lstAdvertiser.DataBind();

            lstAdvertiser.Items.Insert(0, new System.Web.UI.WebControls.ListItem("- ALL -", "0"));
        }
        
        protected void lstSector_Changed(object sender, EventArgs e)
        {
            FillSubSectors();
            FillCategories();

        }

        protected void lstSubSector_Changed(object sender, EventArgs e)
        {
            FillCategories();

        }

        #endregion


        #region Fill Media

        private void FillMediaTypes()
        {

            lstMediaType.DataSource = GetLookupDataSet().Tables["MediaType"];
            lstMediaType.DataBind();


            FillMedia(Utility.ToInt(lstMediaType.SelectedValue));
        }

        private void FillMedia(int MediaTypeCode)
        {


            if (MediaTypeCode > 0)
                lstMedia.DataSource = new DataView(GetLookupDataSet().Tables["Media"], "MediaTypeCode=" + MediaTypeCode.ToString(), "MediaName", DataViewRowState.OriginalRows);
            else
                lstMedia.DataSource = GetLookupDataSet().Tables["Media"];


            lstMedia.DataBind();

            //lstMedia.Items.Insert(0, new ListItem("All", "0"));

            //Utility.SelectListItemByText(lstMedia, "TV"); 

        }


        protected void lstMediaType_SelectedIndexChanged(object sender, EventArgs e)
        {
            FillMedia(Utility.ToInt(lstMediaType.SelectedValue));

            FillAdvertisers();

        }



        #endregion



        #region AutoComplete Functions


        [WebMethod]
        public static string[] AutoComplete_FillProduct(string prefixText, int count, string contextKey)
        {
            //contextKey is brandCode


            string filter = "1=1 ";
            filter += " AND MediaType='NS' AND ProductName LIKE '" + prefixText + "%'";

            //get brand 

            if (contextKey != null && contextKey != "" && contextKey != "0")
            {
                filter += " AND BrandID = " + contextKey;
            }

            if (count == 0) { count = 10; }
            List<string> items = new List<string>(count);

            DataTable dt = GetLookupDataSet().Tables[8];

            DataRow[] drs = dt.Select(filter);

            int counter = 0;
            foreach (DataRow dr in drs)
            {
                items.Add(AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(dr["ProductName"].ToString(), dr["ProductID"].ToString()));


                if (++counter >= count) { break; }
            }

            return items.ToArray();
        }
         
        #endregion





        #region Fill Sector SubSector Category



        #endregion




        protected void btnSearch_Click(object sender, EventArgs e)
        {



            DownloadOnly = chkDownload.Checked;
            if (DownloadOnly && (hdnCategoryIds.Value == ""))
            {
                AjaxFuncs.MsgBox(this.Page,
                                 "To download all the videos, audios, or images related to your category, u must select the category.");
                return;
            }

            bool tmp1 = DateTime.TryParse(calS.SelectedDate.ToShortDateString(), out sDate);
            bool tmp2 = DateTime.TryParse(calE.SelectedDate.ToShortDateString(), out eDate);

            if (sDate < Utility.ToDateTime("01/01/2000"))
                sDate = Utility.ToDateTime("01/01/2000");

            if (eDate < Utility.ToDateTime("01/01/2000"))
                eDate = Utility.ToDateTime("01/01/2000");


            mediaTypeCode = Utility.ToInt(lstMediaType.SelectedValue);

            //mediaCode = Utility.ToInt(lstMedia.SelectedValue);
            foreach (System.Web.UI.WebControls.ListItem itm in lstMedia.Items)
            {
                if (itm.Selected)
                    mediaCodes += itm.Value + ",";
            }
            mediaCodes = mediaCodes.TrimEnd(',');

            programCode = 0;

            sectorCode = Utility.ToInt(lstSector.SelectedValue);
            subSectorCode = Utility.ToInt(lstSubSector.SelectedValue);

            categoryCode = hdnCategoryIds.Value;

            advertiserCode = Utility.ToInt(lstAdvertiser.SelectedValue);



            productCode = hdnProductIDs.Value;

            DownloadOnlyProduct = chkDownloadProduct.Checked;
            //if (DownloadOnlyProduct && (brandCode == 0))
            if (DownloadOnlyProduct && (productCode == ""))
            {
                AjaxFuncs.MsgBox(this.Page,
                                 "To download all the videos, audios, or images related to your product, u must select the product.");
                return;
            }

            sectionCode = Utility.ToInt(lstSection.SelectedValue);
            newsTypeCode = Utility.ToInt(lstNewsType.SelectedValue);
            newsMediaType = lstNewsMediaType.SelectedValue;

            sPrice = tbPriceFrom.Text != "" ? Utility.ToInt(tbPriceFrom.Text) : 0;
            ePrice = tbPriceTo.Text != "" ? Utility.ToInt(tbPriceTo.Text) : 0;

            firstAppearanceOnly = chkFirstAppearance.Checked;


            //if (firstAppearanceOnly == false &&
            //    (sDate == Utility.ToDateTime("01/01/2000") || eDate == Utility.ToDateTime("01/01/2000")) ||
            //    eDate.Subtract(sDate).Days > 31)
            //{
            //    AjaxFuncs.MsgBox(this.Page, "You must select a date range of maximum 1 month");
            //    return;
            //}


            //if (firstAppearanceOnly && (sDate == Utility.ToDateTime("01/01/2000") || eDate.Subtract(sDate).Days != 0))
            //{
            //    AjaxFuncs.MsgBox(this.Page,
            //                     "To see the first appearance of a product, u must select the Date Range of only 1 Day. i.e. Select the same date as Start and End Date.");
            //    return;
            //}

            string cols = "";

            //foreach (ListItem itm in lstFields.Items)
            //{
            //    if (itm.Selected)
            //    {
            //        cols += itm.Value + ", ";
            //    }
            //}

            //if (cols.Contains(","))
            //    cols = cols.Substring(0, cols.LastIndexOf(","));

            Session["SearchMediaCodes_News"] = mediaCodes;
            foreach (System.Web.UI.WebControls.ListItem itm in chklstDays.Items)
            {
                if (itm.Selected)
                    days += itm.Value + ",";
            }
            string reportUrl = "";
            //if (((ImageButton)sender).ID == "btnPdf")
            //{
            //    reportUrl = "report-news-pdf.aspx";
            //}
            //else
            //{
               reportUrl = "report-news.aspx";
            //}

            Response.Redirect(
                  Server.UrlPathEncode(
                      string.Format(
                          reportUrl + "?sd={0}&ed={1}&mtc={2}&mc={3}&s={4}&ss={5}&cc={6}&adv={7}&prod={8}&sc={9}&ntc={10}&nmt={11}&sp={12}&ep={13}&fa={14}&down={15}&downpro={16}&days={17}",
                          sDate.ToShortDateString().Replace("/", "_"), eDate.ToShortDateString().Replace("/", "_"),
                          mediaTypeCode, chkAllMedia.Checked, sectorCode, subSectorCode, categoryCode, advertiserCode, productCode, sectionCode, newsTypeCode, newsMediaType, sPrice, ePrice, firstAppearanceOnly, DownloadOnly, DownloadOnlyProduct, cols,days)));

        }

        //void MakePDF(string fileName, string bgHomeImagePath, string bgSubImagePath )
        //{
        //    Response.ContentType = "application/pdf";

        //    Response.AddHeader("content-disposition", "attachment;filename=" + fileName + ".pdf");

        //    Response.Cache.SetCacheability(HttpCacheability.NoCache);



        //    iTextSharp.text.Image bgHomePage = iTextSharp.text.Image.GetInstance(bgHomeImagePath);
        //    iTextSharp.text.Image bgSubPage = iTextSharp.text.Image.GetInstance(bgSubImagePath);



        //    iTextSharp.text.Rectangle PdfPageSize = new iTextSharp.text.Rectangle(bgHomePage.Width, bgHomePage.Height);

        //    iTextSharp.text.Document pdfDoc = new iTextSharp.text.Document(PdfPageSize);

        //    //bg.Alignment = iTextSharp.text.Image.UNDERLYING;
        //    bgHomePage.Alignment = iTextSharp.text.Image.WRITABLE_DIRECT;
        //    bgSubPage.Alignment = iTextSharp.text.Image.WRITABLE_DIRECT;
         
        //    bgHomePage.ScaleToFit(PdfPageSize.Width, PdfPageSize.Height);
        //    bgSubPage.ScaleToFit(PdfPageSize.Width, PdfPageSize.Height);


        //    bgHomePage.SetAbsolutePosition(0, 0);
        //    bgSubPage.SetAbsolutePosition(0, 0);

        //    PdfWriter writer = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);

        //    //PdfReader reader = new PdfReader(File.OpenRead(bgImagePath));
          

        //    pdfDoc.Open();


        //    pdfDoc.NewPage();
           

        //    PdfContentByte pcb = writer.DirectContentUnder;

        //    pcb.AddImage(bgHomePage);

        //    pdfDoc.Add(new iTextSharp.text.Chunk("\n\n\n\n\n\n\n\n\n\n\n\n\n" + DateTime.Now.ToLongDateString()));


        //    pdfDoc.NewPage();
        //    PdfContentByte pcb1 = writer.DirectContentUnder;
        //    pcb1.AddImage(bgSubPage);

        //    pdfDoc.Add(new iTextSharp.text.Paragraph("\n\n Welcome to Pakistan.\n Welcome to Pakistan.\n Welcome to Pakistan.\n Welcome to Pakistan.\n Welcome to Pakistan.\n Welcome to Pakistan.\n Welcome to Pakistan.\n Welcome to Pakistan.\n Welcome to Pakistan.\n Welcome to Pakistan.\n Welcome to Pakistan.")); 



        //    pdfDoc.CloseDocument();


        //    pdfDoc.Close();

        //    Response.Write(pdfDoc);

        //    Response.End();
        //}



        protected void lnkCategory_Click(object sender, EventArgs e)
        {

            ModalPopupExtender3.Show();
            if (chkCategory.Items.Count == 0)
            {
                lblNoteCategory1.Visible = true;
                btnSaveCategory.Enabled = false;
                lnkProduct.Enabled = false;
            }
            else
            {
                lblNoteCategory1.Visible = false;
                btnSaveCategory.Enabled = true;
                lnkProduct.Enabled = true;
            }
            string[] str = hdnCategoryIds.Value.Split(',');

            for (int i = 0; i < str.Length; i++)
            {
                foreach (System.Web.UI.WebControls.ListItem itm in chkCategory.Items)
                {
                    if (itm.Value == str[i].ToString())
                        itm.Selected = true;
                }
            }
        }
        protected void btnSaveCategory_Click(object sender, EventArgs e)
        {
            string CategoryIDs = string.Empty;
            string CategoryNames = string.Empty;
            foreach (System.Web.UI.WebControls.ListItem itm in chkCategory.Items)
            {
                if (itm.Selected)
                {
                    CategoryIDs += itm.Value + ",";
                    CategoryNames += itm.Text + ", ";
                }
            }
            hdnCategoryIds.Value = CategoryIDs.TrimEnd(',');
            lblSelectedCategory.Text = CategoryNames.TrimEnd(',');
            //BindBrandsAccordingtoCategories(lblSelectedCategory.Text);
            ModalPopupExtender3.Hide();
        }
        protected void lnkProduct_Click(object sender, EventArgs e)
        {
            ModalPopupExtender4.Show();
            DataTable dt = SPs.ProductByCategory(hdnCategoryIds.Value,"NEWS").GetDataSet().Tables[0];
            if (dt.Rows.Count > 0)
            {
                lblNoteProduct.Visible = false;
                btnSaveProduct.Enabled = true;
                chkProduct.DataTextField = "ProductName";
                chkProduct.DataValueField = "ProductID";
                chkProduct.DataSource = dt;
                chkProduct.DataBind();
                string[] str = hdnProductIDs.Value.Split(',');

                for (int i = 0; i < str.Length; i++)
                {
                    foreach (System.Web.UI.WebControls.ListItem itm in chkProduct.Items)
                    {
                        if (itm.Value == str[i].ToString())
                            itm.Selected = true;
                    }
                }
            }
            else
            {
                lblNoteProduct.Visible = true;
                btnSaveProduct.Enabled = false;
                chkProduct.Visible = false;
            }
        }
        protected void btnCancelCategory_Click(object sender, EventArgs e)
        {
            ModalPopupExtender3.Hide();
        }
        protected void btnSaveProduct_Click(object sender, EventArgs e)
        {
            string ProductIDs = string.Empty;
            string ProductNames = string.Empty;
            foreach (System.Web.UI.WebControls.ListItem itm in chkProduct.Items)
            {
                if (itm.Selected)
                {
                    ProductIDs += itm.Value + ",";
                    ProductNames += itm.Text + ",";
                }
            }
            hdnProductIDs.Value = ProductIDs.TrimEnd(',');
            lblSelectedProduct.Text = ProductNames.TrimEnd(',');
            ModalPopupExtender4.Hide();
        }
        protected void btnCancelProduct_Click(object sender, EventArgs e)
        {
            ModalPopupExtender4.Hide();
        }

    }
}